package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.VisitDto;
import com.zzyl.entity.Visit;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.VisitMapper;
import com.zzyl.service.VisitService;
import com.zzyl.utils.MgtThreadLocal;
import com.zzyl.vo.VisitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@Transactional
public class VisitServiceImpl implements VisitService {

    @Autowired
    private VisitMapper visitMapper;

    /**
     * 添加来访
     */
    @Override
    public void add(VisitDto dto) {
        // 否则，允许添加来访
        Visit visit = new Visit();
        BeanUtils.copyProperties(dto, visit);
        visit.setStatus(ReservationStatus.PENDING.getOrdinal());
        Long userId = MgtThreadLocal.getUserId();

        visit.setCreateBy(userId);
        try {
            visitMapper.insert(visit);
        } catch (Exception e) {
            log.info(e + "");
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }
    }

    /**
     * 更新来访
     */
    @Override
    public void update(Long id, VisitDto dto) {
        Visit visit = visitMapper.findById(id);
        if (visit != null) {
            BeanUtils.copyProperties(dto, visit);
            visit.setId(id);
            visit.setUpdateTime(LocalDateTime.now());
            visitMapper.update(visit);
        }
    }

    /**
     * 分页查找来访
     *
     * @param page      页码
     * @param size      每页大小
     * @param name      来访人姓名
     * @param phone     来访人手机号
     * @param status    来访状态
     * @param type      来访类型
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 来访列表
     */
    @Override
    public PageBean<VisitVo> findByPage(int page, int size, String name, String phone, Integer status, Integer type, LocalDateTime startTime, LocalDateTime endTime) {
        PageHelper.startPage(page, size);
        Long userId = MgtThreadLocal.getUserId();
        Page<Visit> byPage = visitMapper.findByPage(page, size, name, phone, status, type, userId, startTime, endTime);
        return PageBean.of(byPage, VisitVo.class);
    }
}

